package com.sms.graduate.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.liaochong.myexcel.core.SaxExcelReader;
import com.sms.graduate.entity.SmsUser;
import com.sms.graduate.entity.importexcel.StudentInfoImport;
import com.sms.graduate.service.SmsDictionaryService;
import com.sms.graduate.service.SmsUserService;
import com.sms.graduate.utils.R;
import com.sms.graduate.utils.TokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.util.*;


@RestController
@RequestMapping("/user")
@Api(tags = "用户信息")
@CrossOrigin(origins = "*")
public class UserController {

    @Autowired
    SmsUserService smsUserService;

    @Autowired
    SmsDictionaryService smsDictionaryService;

    @PostMapping("/userLogin")
    @ApiOperation("用户登录")
    public R userLogin(@RequestParam("userCode") String userCode,@RequestParam("password") String password){
        try {
            password = Base64.getEncoder().encodeToString(password.getBytes());
            SmsUser smsUser = smsUserService.userLogin(userCode, password);
            if (smsUser == null){
                return R.ok("用户名或密码错误");
            }
            String token = TokenUtils.token(userCode);
            return R.ok().put("token",token).put("msg","登陆成功");
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }

    }

    /**
     * 查询教职工人员列表
     */
    @GetMapping("/queryTeacher")
    @ApiOperation("查询教职工人员列表")
    public R queryTeacher(SmsUser smsUser){
        try {
            List<SmsUser> userList = smsUserService.queryTeacher(smsUser);
            return R.ok().put("data",userList);
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
    }

    /**
     * 查询未分配宿舍的学生
     */
    @GetMapping("/noHostelOfStudent")
    @ApiOperation("查询未分配宿舍的学生")
    public R noHostelOfStudent(){
        try {
            List<SmsUser> userList = smsUserService.noHostelOfStudent();
            return R.ok().put("data",userList);
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
    }


    /**
     * 查询人员公共方法
     * @param smsUser
     * @return
     */
    @GetMapping("/queryPeople")
    @ApiOperation("查询人员公共方法")
    public R queryUsers(SmsUser smsUser){
        try {
            List<SmsUser> userList = smsUserService.queryUsers(smsUser);
            return R.ok().put("data",userList);
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
    }

    @PostMapping("/excelImportStudentUser")
    @ApiOperation("导入用户的用户名信息")
    public R excelImportStudentUser(@RequestPart("file") MultipartFile file){
        try {
            final List<StudentInfoImport> artCrowds = new ArrayList();
            SaxExcelReader.of(StudentInfoImport.class).sheet(0).
                    rowFilter(row -> row.getRowNum() > 0)
                    .readThen(file.getInputStream(), d -> {
                        artCrowds.add(d);
                    });
            artCrowds.stream().forEach(a->{
                String s = smsUserService.usercodeByClass(a.getUserMajor(), a.getUserClass(), "0");
                SmsUser smsUser = new SmsUser();
                if(StringUtils.isNotBlank(s)){
                    BigInteger bigInteger = new BigInteger(s);
                    BigInteger bigInteger1 = new BigInteger("1");
                    BeanUtils.copyProperties(a,smsUser);
                    smsUser.setPassword(Base64.getEncoder().encodeToString("123456".getBytes()));
                    //Base64 解密
                    //byte[] decoded = Base64.getDecoder().decode(encoded);
                    //String decodeStr = new String(decoded);
                    smsUser.setUsercode(String.valueOf(bigInteger.add(bigInteger1)));
                    smsUser.setRole("0");
                    smsUser.setRemark("学生");
                }else {
                    String s1 = smsDictionaryService.selectCode(a.getDepartment(), 1);
                    String s2 = smsDictionaryService.selectCode(a.getUserMajor(),2);
                    BeanUtils.copyProperties(a,smsUser);
                    smsUser.setPassword(Base64.getEncoder().encodeToString("123456".getBytes()));
                    //Base64 解密
                    //byte[] decoded = Base64.getDecoder().decode(encoded);
                    //String decodeStr = new String(decoded);
                    smsUser.setUsercode(a.getYearClass()+s1+s2+a.getUserClass()+"01");
                    smsUser.setRole("0");
                    smsUser.setRemark("学生");
                }
                smsUserService.save(smsUser);
            });
            return R.ok("信息保存成功");
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
    }

    @PostMapping("/addTeacherUser")
    @ApiOperation("添加老师信息")
    public R excelImportTeacherUser(@RequestBody SmsUser smsUser, @RequestParam("year") String year,@RequestParam("mouth") String mouth){
      try {
          String s = smsUserService.usercodeByDate(year, mouth);
          smsUser.setPassword(Base64.getEncoder().encodeToString("111111".getBytes()));
          smsUser.setUsercode(s);
          smsUserService.save(smsUser);
          return R.ok("添加成功");
      }catch (Exception e){
          e.printStackTrace();
          return R.error();
      }
    }

    @PostMapping("/updateUserInfo")
    @ApiOperation("修改个人信息")
    public R updateUserInfo(@RequestBody SmsUser smsUser,HttpServletRequest request){
        try {
            String userCode = TokenUtils.getUserCode(request);
            smsUser.setUsercode(userCode);
            smsUserService.updateUserInfo(smsUser);
            return R.ok("信息修改成功");
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
    }

    @PostMapping("/updatePassword")
    @ApiOperation("修改密码")
    public R updatePassword(HttpServletRequest request,@RequestParam("password") String password){
        try {
            String userCode = TokenUtils.getUserCode(request);
            UpdateWrapper<SmsUser> userUpdateWrapper =new UpdateWrapper<>();
            userUpdateWrapper.set(SmsUser.COL_PASSWORD,Base64.getEncoder().encodeToString(password.getBytes()))
                    .eq(SmsUser.COL_USERCODE,userCode);
            smsUserService.update(userUpdateWrapper);
            return R.ok("修改成功");
        }catch (Exception e){
            e.printStackTrace();
            return R.error(e.getMessage());
        }
    }



    @PostMapping("/selectUserInfo")
    @ApiOperation("查询个人信息")
    public R selectUserInfo(HttpServletRequest request){
        try {
            String userCode = TokenUtils.getUserCode(request);
            SmsUser smsUser = smsUserService.selectUserByCode(userCode);
            return R.ok().put("data",smsUser);
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
    }

    @PostMapping("/uploadUserPhoto")
    @ApiOperation("上传用户头像")
    public R uploadUserPhoto(HttpServletRequest request,@RequestParam("file") MultipartFile file){
        try {
            String userCode = TokenUtils.getUserCode(request);
            String originalFilename = file.getOriginalFilename();
            int i = originalFilename.lastIndexOf(".");
            String substring = originalFilename.substring(i);
            SmsUser smsUser = smsUserService.selectUserByCode(userCode);
            if (!StringUtils.isEmpty(smsUser.getUserPhoto())){
                File file1 = new File(smsUser.getUserPhoto());
                if (file1.exists()){
                    file1.delete();
                }
            }
            String filename = smsUser.getUsername()+smsUser.getUsercode()+substring;
            String url = "E:\\photo\\"+smsUser.getUserMajor()+"\\"+smsUser.getUserClass()+"\\";
            File fileUrl = new File(url);
            if (!fileUrl.exists()){
                fileUrl.mkdirs();
            }
            String allURL = url+filename;
            BufferedInputStream bufferedInputStream = new BufferedInputStream(file.getInputStream());
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(allURL));
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = bufferedInputStream.read(b))!= -1){
                bufferedOutputStream.write(b,0,len);
            }
            bufferedInputStream.close();
            bufferedOutputStream.close();
            UpdateWrapper<SmsUser> userUpdateWrapper =new UpdateWrapper<>();
            userUpdateWrapper.set(SmsUser.COL_USERPHOTO,allURL)
                    .eq(SmsUser.COL_USERCODE,userCode);
            smsUserService.update(userUpdateWrapper);
            return R.ok();
        }catch (Exception e){
            e.printStackTrace();
            return R.error(e.getMessage());
        }
    }




    @GetMapping("/selectClassInfo")
    @ApiOperation("查询班级人员信息")
    public R selectClassInfo(SmsUser smsUser,HttpServletRequest request){
        try {
            String userCode = TokenUtils.getUserCode(request);
            smsUser.setUserMajor(smsUserService.selectUserByCode(userCode).getUserMajor());
            Page<SmsUser> page = smsUserService.selectClassInfo(smsUser);
            return R.ok().put("data",page.getRecords()).put("count",page.getTotal());
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
    }

    @GetMapping("/queryMajorClass")
    @ApiOperation("查询专业班级")
    public R queryMajorClass(SmsUser smsUser){
        try {
            List<SmsUser> list = smsUserService.queryMajorClass(smsUser);
            return R.ok().put("data",list);
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
    }

}
